from sqlalchemy import orm
from dbsprockets.metadata import Metadata, MetadataError, NotFoundError, FieldsMetadata
import inspect

class SAModelMetadata(Metadata):
    """
    """
    def __init__(self, provider, identifier=None):
        Metadata.__init__(self, provider, identifier)

    def _do_check_set_item(self, key, value):
        if key in self._models:
            raise MetadataError('%s is already a defined model'%key)

    def _do_get_primary_keys(self):
        return []

    @property
    def _models(self):
        if not hasattr(self, '__models'):
            self.__models = {}
            #pull out all models associated with this provider's metadata
            for mapper in orm._mapper_registry.keys():
                if mapper.tables[0].metadata.bind == self.provider.engine:
                    self.__models[mapper.class_.__name__] = mapper.class_
        return self.__models

    def _do_get_foreign_keys(self):
        return []

    def _do_get_item(self, item):
        if item in self._models:
            return self._models[item]
        raise NotFoundError

    def _do_keys(self):
        keys = self._models.keys()
        keys.sort()
        return keys

    def _do_is_nullable(self, item):
        return False

class ModelFieldsMetadata(FieldsMetadata):
    def __init__(self, provider, identifier):
        Metadata.__init__(self, provider, identifier)
        for mapper in orm._mapper_registry.keys():
            if mapper.tables[0].metadata.bind == self.provider.engine and mapper.class_.__name__==identifier:
                self.table = mapper.tables[0]
                break;